﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Util.Extension;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class ExchangeRateController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        public ExchangeRateController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.ExchangeRates
                           select new
                           {
                               id = y.Id,
                               fromCurrency = y.From,
                               toCurrency = y.To,
                               updateType = y.Update,
                               price = y.Price,
                               buyDownFloat = y.Buy,
                               sellUpFloat = y.Sell,
                               updatetime = y.Updatetime
                           };


                res.Code = 0;
                res.Count = data.Count();
                res.Data = await data.Skip((page - 1) * limit).Take(limit).OrderBy(k => k.updatetime).ToListAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }


        #region 添加
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(ExchangeRate model)
        {
            Result res = new Result();
            try
            {
                if (!ToExists(model.From, model.To))
                {
                    model.Updatetime = DateTime.Now;
                    _context.ExchangeRates.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑信息
        public async Task<IActionResult> Edit(int id)
        {
            ExchangeRate currency = await _context.ExchangeRates.FirstOrDefaultAsync(e => e.Id == id);
            if (currency == null)
            {
                return NotFound();
            }
            return View(currency);
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(ExchangeRate item)
        {
            Result res = new Result();
            try
            {
                if (!ToExists(item.From, item.To, item.Id))
                {
                    ExchangeRate model = await _context.ExchangeRates.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.From = item.From;
                        model.To = item.To;
                        model.Update = item.Update;
                        model.Price = item.Price;
                        model.Buy = item.Buy;
                        model.Sell = item.Sell;
                        model.Updatetime = DateTime.Now;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="fromCurrency"></param>
        /// <param name="toCurrency"></param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(string fromCurrency, string toCurrency)
        {
            Result res = new Result();
            try
            {
                ExchangeRate model = await _context.ExchangeRates.FirstOrDefaultAsync(e => e.From == fromCurrency && e.To == toCurrency);

                _context.ExchangeRates.Remove(model);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool ToExists(string fromCurrency, string toCurrency, int id = 0)
        {
            if (id == 0)
                return _context.ExchangeRates.Any(e => e.From == fromCurrency && e.To == toCurrency);
            else
                return _context.ExchangeRates.Any(e => e.Id != id && e.From == fromCurrency && e.To == toCurrency);
        }
        #endregion
    }
}
